<?php

namespace App\Models\MainDB;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GiftBackpack extends Model
{
    protected $table = 'app_user_backpack';

    protected $primaryKey = 'id';

    public $timestamps = false;


    public function userBackpack(int $userId)
    {
        $query = self::query();
        $query->where('user_id', $userId);
        return $query->get();
    }

    public function batchIncGift(int $userId, array $update)
    {
        if (! empty($update)) {
            $model = new GiftBackpack();
            $table = $model->getTable();
            $sql = "update {$table} set  `gift_num` = case `gift_id`";
            foreach ($update as $giftId => $count) {
                $sql .= "when {$giftId} then `gift_num` + {$count} ";
            }
            $sql .= "else `gift_num` end where user_id = '{$userId}'";

            DB::update($sql);
        }
    }

    /**
     * 背包礼物变动
     *
     * @param integer $uid
     * @param integer $gift_id 礼物ID
     * @param integer $type 1增加 -1减少
     * @param integer $number 数量
     * @param integer $scene 场景 4:draw活动
     * @param string $desc 描述
     * @return void
     */
    public function addGift(int $uid, int $gift_id, int $type, int $number,int $scene = 4, string $desc)
    {
        if (empty($number)) {
            return true;
        }
        $giftMallInfo = app('model_gift')->where('id', $gift_id)->first();
        if (!$giftMallInfo) {
            return false;
        }
        try {
            $UserBackpack = [];
            switch ($type) {
                case 1:
                    #查询用户背包是否有该礼物位
                    if ($this->where(['user_id' => $uid, 'gift_id' => $gift_id])->first()) {
                        $this->where(['user_id' => $uid, 'gift_id' => $gift_id])->increment('gift_num', $number);
                    } else {
                        #奖励入背包
                        $UserBackpack = [
                            'user_id' => $uid,
                            'gift_id' => $gift_id,
                            'gift_num' => $number,
                        ];
                    }
                    if (!empty($UserBackpack)) {
                        if (!$this->insert($UserBackpack)) {
                            return false;
                        }
                    }
                    break;
                case -1:
                    $where = [
                        'user_id' => $uid,
                        'gift_id' => $gift_id,
                    ];
                    $userbackpackInfo = $this->where($where)->first();
                    if (!$userbackpackInfo) {
                        return false;
                    }
                    if (!$this->where($where)->decrement('gift_num', $number)) {
                        return false;
                    }
                    break;
                default:
                    return false;
                    break;
            }
            # 入背包赠送记录
            $UserBackpackLog = [
                'user_id' => $uid,
                'type' => $type,
                'gift_id' => $gift_id,
                'gift_num' => $number,
                'scene' => $scene,
                'desc' => $desc
            ];
            $UserBackpackLogModel = app('model_user_backpack_log');
            $UserBackpackLogModel->fill($UserBackpackLog);
            if (!$UserBackpackLogModel->save()) {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
        return true;
    }


    // 抽奖批量加礼物
    public function addPrizes(int $userId, array $draws, $desc = '')
    {
        if (! empty($draws)) {
            $scene = 4;
            $backpack = $this->userBackpack($userId);
            $insert = [];
            $update = [];
            $insertLog = [];
            foreach ($draws as $prizeId => $prize) {
                $giftId = $prizeId;
                if ($backpack->where('gift_id', $giftId)->isNotEmpty()) { // 礼物存在背包
                    $update[$giftId] = $prize['count'];
                } else { // 礼物不存在背包
                    $insert[] = [
                        'user_id' => $userId,
                        'gift_id' => $giftId,
                        'gift_num' => $prize['count'],
                    ];
                }

                # 入背包赠送记录
                $insertLog[] = [
                    'user_id' => $userId,
                    'type' => 1,
                    'gift_id' => $giftId,
                    'gift_num' => $prize['count'],
                    'scene' => $scene,
                    'desc' => $desc
                ];
            }
            if ($insert) {
                Model::insert($insert);
            }
            if ($update) {
                $this->batchIncGift($userId, $update);
            }
            if ($insertLog) {
                app('model_user_backpack_log')->insert($insertLog);
            }
        }
    }
}
